package com.huawei.chengdu.meetingdemo.util;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Author: xurui 30031276
 * Created on 2022/8/27 11:19
 * Desc：
 */
public class StringUtil {
    private static final String TAG = "StringUtil";

    /**
     * char数组转byte数组
     *
     * @param chars 源
     * @return 数据
     */
    public static byte[] getBytes(char[] chars) {
        CharBuffer charBuffer = CharBuffer.wrap(chars);
        ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
        byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
                byteBuffer.position(), byteBuffer.limit());
        Arrays.fill(byteBuffer.array(), (byte) 0);
        return bytes;
    }

    /**
     * 清除字符数组
     *
     * @param chars s
     */
    public static void clearChars(char[] chars) {
        if (chars == null) {
            return;
        }
        for (int i = 0; i < chars.length; i++) {
            chars[i] = 0;
        }
    }

    /**
     * 判断char[]是否空
     *
     * @param chars s
     * @return result
     */
    public static boolean isEmptyChars(char[] chars) {
        return chars == null || chars.length == 0;
    }

    /**
     * 检查是否合法Ip
     *
     * @param ip 地址ip
     * @return boolean
     */
    public static boolean isRightIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }

        String newIp = ip.trim();
        if (newIp.length() < 6 || newIp.length() > 15) {
            return false;
        }
        try {
            String rule
                    = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
            Pattern pattern = Pattern.compile(rule);
            Matcher matcher = pattern.matcher(ip);
            return matcher.matches();

        } catch (PatternSyntaxException ex) {
            return false;
        }
    }

    public static boolean isOverMaxLen(String str, int maxLen) {
        int strBytesLen = 0;
        try {
            strBytesLen = str.getBytes("UTF-8").length;
        } catch (UnsupportedEncodingException e) {
            LogUtil.error("isOverMaxLen getBytes error");
        }
        if (str.length() > maxLen || strBytesLen > maxLen) {
            return true;
        }
        return false;
    }

    public static boolean checkString(String str) {
        int bytesLength;
        try {
            bytesLength = str.getBytes("UTF-8").length;
        } catch (UnsupportedEncodingException e) {
            return false;
        }
        if (bytesLength > 128 || str.length() > 128) {
            return false;
        }
        return true;
    }
}
